package com.lge.clock.alarmclock; 
   
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;

import android.content.res.Configuration;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;

import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;

import android.widget.CheckedTextView;
import android.widget.FrameLayout;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.widget.SimpleCursorAdapter.ViewBinder;

/* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
 * 15/02/12 pradeep.gk@lge.com
 * To support arabic and farsi number conversion support.
 */
 import com.lge.clock.util.CommonUtil;
/* LGSI_CHANGE_E: Arabic and Farsi number conversion support */

import com.lge.clock.R;

/**
 * 2010.08.31
 * @author donggeun.kim
 *
 */
public class AlarmDeleteListActivity extends Activity implements View.OnClickListener, OnItemClickListener { 

	private LayoutInflater mFactory;
	private ListView list;
	private LinearLayout command_layout; 
	private Button mDeleteButton, mCancel;
	private Menu m_menu;
	private int listCount = 0;

	private TextView mDeleteCount;
	private TextView selectAllText;
	private final String tag = "AlarmDeleteListActivity";
	
	private Map<String, String> storageOnOffs;
	private Map<String, String> storageCheck;
	
	public static String save_id = "";
	 
	private Cursor cursorQuery;
	public static Context mContext = null;
	private ContentResolver resolver;

	// 20101019_mhkwon_Block multi touch [[
	private static boolean bBlockMultiTouchFlag = false;
	// 20101019_mhkwon_Block multi touch ]]
	private MediaPlayer mplayer; // 20101104_mhkwon_QG15889_Touch_tone 
    private AudioManager mAudioManager = null;
	
	private Map<String, String> storageWidgetYN;
	private boolean stateYN = false;
	
	private static final int DIALOG_DELETE = 2;
    private int delete_msg = -1;
    private int delete_title = -1;
    private AlertDialog.Builder mDeleteDialog;	
	/**
	 * Play Touch Tone Thread
	 */
	// 20101104_mhkwon_QG15889_Touch_tone  [[
    Runnable playTouchToneThread = new Runnable() {
        public void run() {
            int getRingerMode = 0;
            final String strMODE_RINGER = "mode_ringer";

            if(mAudioManager == null) {
            	ContentResolver mContentResolver = getContentResolver();
                mAudioManager = (AudioManager)AlarmDeleteListActivity.this.getSystemService(Context.AUDIO_SERVICE);
                getRingerMode = android.provider.Settings.System.getInt(mContentResolver, strMODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
            }
            else {
            	getRingerMode = mAudioManager.getRingerMode();
            }

            if (Settings.System.getInt(resolver, Settings.System.SOUND_EFFECTS_ENABLED, 0) == 1
            		&& getRingerMode == AudioManager.RINGER_MODE_NORMAL ){
            	mplayer.start();
            }
        };
    };
    // 20101104_mhkwon_QG15889_Touch_tone  ]]
	          
	@Override 
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.alarm_delete_list);
        
		resolver = getContentResolver();
		    
        mplayer = MediaPlayer.create(this, R.raw.effect_tick);
		
        /*[START] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/
//		Intent i = getIntent();
//		if (i != null) {
//			if (mContext != null) {
//				AlarmDeleteListActivity aa = (AlarmDeleteListActivity)mContext;
//				Log.d(tag, "===========AlarmDeleteListActivity kill===================");
//				aa.finish();
//			}
//		}
        /*[END] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/
		
		list = (ListView)findViewById(R.id.alarms_list);
		if ( list != null ) {
			list.setOnItemClickListener(this);
			registerForContextMenu(list);
		}
    
		command_layout = (LinearLayout)findViewById(R.id.command_layout);
		mDeleteButton  = (Button)findViewById(R.id.deleteButton);
		mCancel        = (Button)findViewById(R.id.cancel);

		mDeleteButton.setOnClickListener(this);
		mDeleteButton.setEnabled(false);
		mCancel.setOnClickListener(this);

		mDeleteCount = (TextView)findViewById(R.id.SelectedItem);
		setSelectedItem(0);
		
		CheckedTextView checkAll = (CheckedTextView)findViewById(R.id.checkall);
		checkAll.setOnClickListener(this);
		
		selectAllText = (TextView) findViewById(R.id.DeleteTitleString);
		selectAllText.setOnClickListener(this);
		
		
		// 20101014_mhkwon_SE10016_AlarmDeleteListActivity_ANR [[
		Handler setNextAlertHandler = new Handler();
		setNextAlertHandler.postDelayed(setNextAlertThread, 0);
		// 20101014_mhkwon_SE10016_AlarmDeleteListActivity_ANR ]]
		
	    mContext = this;
	    mFactory = LayoutInflater.from(this);
	    
	    command_layout.setVisibility(View.VISIBLE);

	    list_func();
	    
	    if ( list != null ) {
	    	((AlarmListCursorAdapter) list.getAdapter()).setCheckboxVisility(true);
		    ((AlarmListCursorAdapter) list.getAdapter()).notifyDataSetInvalidated();
	    }
	}
	
	Runnable setNextAlertThread = new Runnable() {
	    public void run() {
	    	Alarms.disableExpiredAlarms(AlarmDeleteListActivity.this, false);
		    Alarms.setNextAlert(AlarmDeleteListActivity.this);
	    };
	};
	
	// 20100827_mhkwon_SE6988_Save selected list item when resume. [[
    @Override
    protected void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        Log.d(tag, "onSaveInstanceState(Bundle state)");
        
        /*[START] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/
        state.putSerializable("suein", (Serializable) storageCheck);
        state.putInt("CheckedItem", deleteCount);
        
//        Map.Entry<String, String>temp;
//        Set ee = storageCheck.entrySet();
//        Iterator ii =  ee.iterator();
//        String selectedItems = "";
//	    	
//        while(ii.hasNext()) {
//        	temp = (Map.Entry<String, String>)ii.next();
//        	if ("1".equals(temp.getValue())) {
//        		selectedItems = selectedItems + "1";
//        		Log.d(tag, "onSaveInstanceState : "+temp.getKey()+", "+temp.getValue()+", "+selectedItems);       
//        	}
//        	else {
//        		selectedItems = selectedItems + "0";
//        		Log.d(tag, "onSaveInstanceState : "+temp.getKey()+", "+temp.getValue()+", "+selectedItems);       
//        	}
//        }
//        state.putString("ALARM_LIST_SELECTED_ITEM", selectedItems);
        /*[END] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/
        
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle state) {
        Log.d(tag, "onRestoreInstanceState(Bundle state)");
        deleteCount = state.getInt("CheckedItem", deleteCount);
        setSelectedItem(deleteCount);

        /*[START] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/
        HashMap<String, String> backupCheckStat = (HashMap<String, String>) state.getSerializable("suein");
        if(backupCheckStat != null){
        	
        	storageCheck = (HashMap<String, String>) state.getSerializable("suein");
        	//if item is checked in list
        	if(storageCheck != null && storageCheck.containsValue("1")){
        		mDeleteButton.setEnabled(true);
        	} //End Of if
        	
        	//if all item is checked in list
        	if(storageCheck != null && !storageCheck.containsValue("0")){
        		CheckedTextView checkAll = (CheckedTextView) findViewById(R.id.checkall);
        		checkAll.setChecked(true);
        	} //End Of if
        	
        } //End Of if
        
//        String selectedItems = "";
//        Set ee = storageCheck.entrySet();
//        Iterator ii = ee.iterator();
//        Map.Entry<String, String>temp;
//        
//        super.onRestoreInstanceState(state);
//        selectedItems = state.getString("ALARM_LIST_SELECTED_ITEM");
//
//     	// WBT TD2170327804
//        if( selectedItems != null ){
//	        try {
//	        	int nSelectedCnt = selectedItems.length();
//	        	for ( int i = 0; i < nSelectedCnt; i++ ) {
//	        		Log.d(tag, "===SelectedItems.substring(i,i)===" + selectedItems.substring(i,i));
//	        		if (ii.hasNext()) {
//	        			temp = (Map.Entry<String, String>) ii.next();
//	
//	        			if ("1".equals(selectedItems.substring(i,i))) {
//	        				Log.d(tag, "\"1\".equals(SelectedItems.substring(i,i)) = 1");
//	        				storageCheck.put((String)temp.getKey(),  "1");
//	        			}
//	        			else {
//	        				Log.d(tag, "\"1\".equals(SelectedItems.substring(i,i)) = 0");
//	        				storageCheck.put((String)temp.getKey(),  "0");
//	        			}
//	        		}
//	        	}
//	        } catch (Exception e) {
//	        	e.printStackTrace();
//	        }
//        }
        /*[END] 2012.03.23 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #147822*/

    }    
    // 20100827_mhkwon_SE6988_Save selected list item when resume. ]]
    
	@Override
	 protected void onNewIntent(Intent i) {
		super.onNewIntent(i);
		Log.d(tag, "onNewIntent AlarmDeleteListActivity");
	}
	
	@Override
	protected void onResume() {
		Log.d(tag, "onResume");
		super.onResume();
	}

	private static final String[] PROJECTION_1 = new String[] { "_id",  "hour",  "minutes", "daysofweek",  "enabled", "widget_yn" };

	 
	/**
	 * when listview is show, option is different.
	 * when not deleted. ==> gubun = "TOTAL"
	 * 
	 *   ==> when firstIndex is not widget, it is first Row's index (why need
	 * 
	 * when delete mode. ==> gubun = "OK"
	 * 
	 * @param gubun
	 */
	 
    private void list_func() {
    	// 20100827_mhkwon_SE6988_Save selected list item when resume. [[
    	boolean bNew_stroagecheck_flag = false;
    	storageOnOffs = new HashMap<String, String>();
		
		if (storageCheck == null) {
		    storageCheck = new HashMap<String, String>();
		    bNew_stroagecheck_flag = true;
		}
		// 20100827_mhkwon_SE6988_Save selected list item when resume. ]]
		
		storageWidgetYN = new HashMap<String, String>();		
		   
		if( cursorQuery != null) {
			cursorQuery.close();
		}
		
		cursorQuery = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION_1, "widget_yn = 'N'", null, "hour, minutes, _id");
//		startManagingCursor(cursorQuery);
		
		//cursorQuery = managedQuery(Uri.parse(Alarms.CONTENT_ALARMS_URI_STRING.concat("?queryType=1")), PROJECTION_1, "widget_yn = 'N'", null, "hour, minutes, _id");

		if(cursorQuery != null) {
			listCount = cursorQuery.getCount();
		}
		if ( listCount == 0 ) {
			// WBT TD#142762 Fixed Start
			if (list != null ) {
				list.setVisibility(View.GONE);
			}
			// WBT TD#142762 Fixed End
			 
			if ( m_menu != null )
				m_menu.clear();
		} else {
			//int ccc = 0;
			if ( list != null )
				list.setVisibility(View.VISIBLE);
			if( cursorQuery != null) {
				if ( cursorQuery.moveToFirst() ) {
					  do { 
						  storageOnOffs.put((String)cursorQuery.getString(0), (String)cursorQuery.getString(4));
						  
						  // 20100827_mhkwon_SE6988_Save selected list item when resume. [[
						  if (bNew_stroagecheck_flag == true) {
						      storageCheck.put((String)cursorQuery.getString(0), "0");
						  }
						  // 20100827_mhkwon_SE6988_Save selected list item when resume. ]]
						  
						  if ("Y".equalsIgnoreCase( (String)cursorQuery.getString(5) )) {
							  storageWidgetYN.put((String)cursorQuery.getString(0), "Y");
							  
						  } else if ("N".equalsIgnoreCase( (String)cursorQuery.getString(5) )) {
							  storageWidgetYN.put((String)cursorQuery.getString(0), "N");
							  //++listINDEXCount;
						  }///////////////////////////////////////////////////////////////// 
					  } while(cursorQuery.moveToNext());
				}
			}
		}
			
		if (stateYN == true) {
			if (listCount == 0) {
				((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
        	} else {
        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
        	}
		} else {
			if (listCount == 0) {
				((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
        	} else {
        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
        	}
		}
			 
		String[] from = new String[] { }; 
		int[] to = new int[] { };
		// WBT TD#142762 Fixed Start
		if (list != null) {
			if(cursorQuery != null){
				list.setAdapter(new AlarmListCursorAdapter(this,   
						R.layout.alarm_main_listitem,
						cursorQuery,
						from, to));	
			}
		}
		// WBT TD#142762 Fixed End
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    		switch(newConfig.orientation){
    			case Configuration.ORIENTATION_LANDSCAPE:
		   			stateYN = true;
		   			if (listCount == 0) {
		        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
		        	} else {
		        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
		        	}
		   			break;

    			case Configuration.ORIENTATION_PORTRAIT:
    				stateYN = false;
		        	if (listCount == 0) {
		        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.VISIBLE);
		        	} else {
		        		((LinearLayout)findViewById(R.id.noTitleTop)).setVisibility(View.GONE);
		        	}
		        	break;
		        	
		        default :
		        	break;
    		}
    }
	
	/**
	 * 	Dispatch Hardware Key Event
	 */
    @Override                
    public boolean dispatchKeyEvent(KeyEvent event) {
    	if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
    		finish();
    	}
    	   
    	return super.dispatchKeyEvent(event);
	}
    
	/*  
	 * (Handle the buttons) .
	 */ 
	public void onClick(View button) {
		Map.Entry<String, String>temp;
        Set ee;
        Iterator ii;
		/*
		 * if (!button.isEnabled()) return;
		 */                     
		switch (button.getId()) {
			case R.id.cancel :
                finish();
                break;
                                
		    case R.id.deleteButton : 
		    	boolean delKey_checkYN = false;
		    	ee = storageCheck.entrySet();
		    	ii =  ee.iterator();
		    	mDeleteButton.setClickable(false);
		        mCancel.setClickable(false);
		              
		    	while(ii.hasNext()) {
		    		temp = (Map.Entry<String, String>) ii.next();
		    		if ("1".equals(temp.getValue())) {
		    			delKey_checkYN = true ;
		    			break;      
		    		}               
		    	}
		               
		    	if (delKey_checkYN == false) {        
		    		return;
		    	}
		    	else {  
		    		deleteAllYN();
		    	}
		    	break;
		    	
		    case R.id.checkall :
		    	Log.d(tag, "checkAll click");
		    	CheckedTextView checkAll = (CheckedTextView) findViewById(R.id.checkall);
		    	ee = storageCheck.entrySet();
		    	ii =  ee.iterator();
		    	if( checkAll.isChecked() == false ) {
//		    		Log.d(tag, "checkAll = " + true);
		    		while(ii.hasNext()) {
		    			temp = (Map.Entry<String, String>) ii.next();
		                storageCheck.put((String)temp.getKey(),  "1");
		    		}
		            
		    		if ( list != null ) {
		    			((AlarmListCursorAdapter)list.getAdapter()).setCheckboxVisility(true); 
						((AlarmListCursorAdapter)list.getAdapter()).notifyDataSetInvalidated();
		    		}
		    		checkAll.setChecked(true);
					mDeleteButton.setEnabled(true);
					deleteCount = listCount;
		    	}
		    	else {
		    		while( ii.hasNext() ) {
		    			temp = (Map.Entry<String, String>) ii.next();
		                storageCheck.put((String)temp.getKey(), "0");
		    		}
					
		    		if ( list != null ) {
		    			((AlarmListCursorAdapter)list.getAdapter()).setCheckboxVisility(true); 
						((AlarmListCursorAdapter)list.getAdapter()).notifyDataSetInvalidated();
		    		}
		    		checkAll.setChecked(false);
					mDeleteButton.setEnabled(false);
					deleteCount = 0;
		    	}
		    	
		    	setSelectedItem(deleteCount);
		    	break;
		    	
		    case R.id.DeleteTitleString :
		    	CheckedTextView checkAll1 = (CheckedTextView) findViewById(R.id.checkall);
		    	ee = storageCheck.entrySet();
		    	ii =  ee.iterator();
		    	if(checkAll1.isChecked()) {
		    		Log.d(tag, "checkAll = " + checkAll1.isChecked());
		    		checkAll1.setChecked(false);
		    		while(ii.hasNext()) {
		    			temp = (Map.Entry<String, String>) ii.next();
		                storageCheck.put((String)temp.getKey(), "0");
		    		}
					  
		    		if ( list != null ) {
		    			((AlarmListCursorAdapter) list.getAdapter()).setCheckboxVisility(true); 
						((AlarmListCursorAdapter) list.getAdapter()).notifyDataSetInvalidated();
		    		}

					mDeleteButton.setEnabled(false);
					deleteCount = 0;
		    	}
		    	else {
		    		Log.d(tag, "checkAll = " + checkAll1.isChecked());
		    		checkAll1.setChecked(true);
		    		while(ii.hasNext()) {
		    			temp = (Map.Entry<String, String>) ii.next();
		                storageCheck.put((String)temp.getKey(), "1");
		    		}
		            
		    		if ( list != null ) {
		    			((AlarmListCursorAdapter) list.getAdapter()).setCheckboxVisility(true); 
						((AlarmListCursorAdapter) list.getAdapter()).notifyDataSetInvalidated();
		    		}
	  
					mDeleteButton.setEnabled(true);
					deleteCount = listCount;
		    	}
		    	setSelectedItem(deleteCount);
		    	break;
		    
		    default :
		    	break;
		}
	}
	
	public void deleteAllYN() {
		if(mDeleteDialog != null)
			removeDialog(DIALOG_DELETE);
		showDialog(DIALOG_DELETE);
	}

    private void setDeleteString() {
		Map.Entry<String, String>temp;
		Set ee = storageCheck.entrySet();
        Iterator ii = ee.iterator();   
        int nDeleteCountYN = 0;
       
        while(ii.hasNext()) {
        	temp = (Map.Entry<String, String>) ii.next();
     	
        	if ("1".equals(temp.getValue())) {
        		nDeleteCountYN++;
        	}
        }
    
		if (nDeleteCountYN == listCount ) {
			delete_title = R.string.menu_deleteall;
			delete_msg = R.string.sp_delete_all_NORMAL;
		} else if ( nDeleteCountYN == 1 ) {
			delete_title = R.string.menu_multiselect;
			delete_msg = R.string.delete_alarm_confirm;
		} else {
			delete_title = R.string.menu_multiselect;
			delete_msg = R.string.delete_some;
		}    	
	}
    
	/**
	 * Method onCreateDialog.
	 */
	@Override 
	protected Dialog onCreateDialog(int id) {
        switch (id) {
            case (DIALOG_DELETE) : {
            	setDeleteString();
            	mDeleteDialog = new AlertDialog.Builder(this);
            	return mDeleteDialog.setTitle(delete_title)
            	.setIconAttribute(android.R.attr.alertDialogIcon)
            	.setMessage(delete_msg)
            	.setCancelable(true)
            	.setPositiveButton(android.R.string.yes,                
                		new DialogInterface.OnClickListener() {
                			public void onClick(DialogInterface dialog, int which) {
                				mDeleteButton.setClickable(true);
                				mCancel.setClickable(true);
                				delete();
                				Toast.makeText(AlarmDeleteListActivity.this, getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
                			}
                		})
            	.setNegativeButton(android.R.string.no,
                		new DialogInterface.OnClickListener() {
                			public void onClick(DialogInterface dialog, int which) {
                				mDeleteButton.setClickable(true);
                				mCancel.setClickable(true);
                			}
                		})
            	.setOnCancelListener(new OnCancelListener() { 
        			
        			@Override
        			public void onCancel(DialogInterface dialog) {
        				// TODO Auto-generated method stub
        				mDeleteButton.setClickable(true);
        				mCancel.setClickable(true);
        			}
        		})
            	.create();
        	}
            default :
        }
        return null;
    }
	
	public void delete() {
		Map.Entry<String, String>temp;
        Set ee = storageCheck.entrySet();
        Iterator ii = ee.iterator();
           
        StringBuffer ids = new StringBuffer(30);
        ids.append("");
          
        NotificationManager nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        while( ii.hasNext() ) {
        	temp = (Map.Entry<String, String>)ii.next();
            //storageCheck.put((String)temp.getKey(),  "1");
            
            if ( "1".equals(temp.getValue()) ) {
            	ids.append(temp.getKey() + ",");
            	nm.cancel( Integer.parseInt(temp.getKey()) );
            	killOnProcess2(temp.getKey());
            }
        }
           
        if ( ids.toString().trim().length() > 0 ) {
        	int ch = ids.toString().lastIndexOf(',');
        	String deleteTarget = "_id IN (" +  ids.toString().substring(0, ch) + ") ";
        	String snoozeDeleteTarget = "aid IN (" +  ids.toString().substring(0, ch) + ") ";
	        /**
	         * Removes an existing Alarm.  If this alarm is snoozing, disables
	         * snooze.  Sets next alert.
	         */ 
	        getContentResolver().delete(ALProvider.CONTENT_ALARMS_URI, deleteTarget, null); 
	        getContentResolver().delete(ALProvider.CONTENT_CALCU_URI, snoozeDeleteTarget, null);
	              
	        Alarms.setNextAlert(this); 

	        finish();
        }    
	}

	/**
	 * donggeun.kim
	 * case2) during alarm, when alarm delete in delete mode, alarm activity is killed.
	 * @param _id
	 */
	private void killOnProcess2(String id) {
    	Log.d(tag,"===Delete====_id===>" + id);
    	NotificationManager nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel( Integer.parseInt(id) );
                	
    	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(id);
    	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection [[
    	if (aa == null ) {
    		return;
    	}
    	
    	Log.d(tag,"==OK=deleted====_id===>" + id);
    	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection ]]
    	aa.forceStop();
    	AlarmAlert.mAlarmSavings.remove(id);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if( cursorQuery != null) {
			cursorQuery.close();
		}		
	}

	@Override
	protected void onPause() {
		super.onPause();
	} 
 
	@Override
	protected void onRestart() {
		super.onRestart();
	} 

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();		
	}

	/**
     * view holder
     * @author suein1209.kim
     */
    private final class ViewHolder {
    	private FrameLayout rowLayout;
    	private TextView tvMINUTES;
    	private TextView tvHOUR;
    	private TextView tvAPM;
    	private TextView tvDAYS;
    	private TextView tvGUBUN;
    	private CheckedTextView checkView;
    	private LinearLayout eee;
    	private String id;
	} //End Of class ViewHolder
	
	//// private class       
//=========== Begin =============================================================
	private class  AlarmListCursorAdapter extends ResourceCursorAdapter {
		
		protected int[] mFrom;
	    protected int[] mTo;
	    // Just for test 
		private boolean mIsShowCheck = false;
	    private int mStringConversionColumn = -1;
	    private CursorToStringConverter mCursorToStringConverter;
	    private ViewBinder mViewBinder;
	    private String[] mOriginalFrom;
	    private final WeakHashMap<View, View[]> mHolders = new WeakHashMap<View, View[]>();
		private AlarmDeleteListActivity testlist;
		
		private AlarmListCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c);
	        mTo = to;
	        mOriginalFrom = from;
	        findColumns(from);
	        testlist = (AlarmDeleteListActivity)context;
	    }   
		
	    public void setCheckboxVisility(boolean visibility) {
			this.mIsShowCheck = visibility;
		} 
		
//		public boolean getCheckboxVisiblity(){
//			return this.mIsShowCheck;
//		}
	    
//	    @Override
//	    public View newView(Context context, Cursor cursor, ViewGroup parent) {
//	        return generateViewHolder(super.newView(context, cursor, parent));
//	    } 
	    
	    @Override
	    public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View ret = mFactory.inflate(R.layout.alarm_main_listitem, parent, false);
            
            ViewHolder holder = new ViewHolder();
            holder.tvMINUTES = (TextView)ret.findViewById(R.id.minutes);
            holder.tvHOUR = (TextView)ret.findViewById(R.id.hour);
            holder.tvAPM = (TextView)ret.findViewById(R.id.apm);
            holder.tvDAYS = (TextView)ret.findViewById(R.id.daysofweek);
            holder.tvGUBUN = (TextView)ret.findViewById(R.id.gubun);
            holder.checkView = (CheckedTextView)ret.findViewById(R.id.CheckBox);
            holder.eee = (LinearLayout)ret.findViewById(R.id.eee);
            
            ret.setTag(holder);
            return ret;
        } 

//	    @Override
//	    public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
//	        return generateViewHolder(super.newDropDownView(context, cursor, parent));
//	    }

//	    private View generateViewHolder(View v) {
//	        final int[] to = mTo;
//	        final int count = to.length;
//	        final View[] holder = new View[4];
//
//	        for (int i = 0; i < count; i++) {
//	            holder[i] = v.findViewById(to[i]);
//	        }
//	         
//	        mHolders.put(v, holder);
//
//	        return v;
//	    }
	    
	    @Override
	    public void bindView(final View view, Context context, Cursor cursor) {
	    	//final View[] holder = mHolders.get(view);
	    	//final ViewBinder binder = mViewBinder;
	    	//final int count = mTo.length;
	    	//final int[] from = mFrom;
	    	if(cursor != null) {
	    		final Alarms.DaysOfWeek daysOfWeek = new Alarms.DaysOfWeek( cursor.getInt(3) );
	  	      
		    	// _id = primary key ,  enabled = 'On/Off'  
		    	final String id = Integer.toString(cursor.getInt(0));
		    	//final String enabled = cursor.getString(4); 
		    	final int hour = cursor.getInt(1);
		    	final int minutes = cursor.getInt(2);
		    	
		    	final ViewHolder holder = (ViewHolder)view.getTag();
	                                   
		    	/*[START] 2012.03.02 suein1209.kim set check box listener*/
		    	holder.id = id;
		    	holder.checkView.setFocusable(false);
		    	holder.checkView.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						final CheckedTextView checkView = (CheckedTextView)v.findViewById(R.id.CheckBox);
						checkEvent(id, checkView);
					}
				});
		    	/*[END] 2012.03.02 suein1209.kim set check box listener*/
		    	
		    	
//		    	rowLayout.setOnClickListener(new OnClickListener() {
//					
//					public void onClick(View v) {
//						
//						final CheckedTextView checkView = (CheckedTextView)v.findViewById(R.id.CheckBox);
//						checkEvent(id, checkView );
//					}
//					
//				});
		    	
		    	/*
		    	rowLayout.setOnTouchListener(new OnTouchListener(){
		    		public boolean onTouch(View view, MotionEvent e){
		    			
		    			rowLayout = (FrameLayout)view.findViewById(R.id.rowLayout);
		    	    	//final TextView titleView    = (TextView)view.findViewById(R.id.title_text);
		    			   
		    	    	//storageView.put(_id,  rowLayout ) ;
		    	    	///////////////////////////////////////////////////////////////////////
		    	    	tvMINUTES = (TextView)view.findViewById(R.id.minutes);
		    	    	tvHOUR = (TextView)view.findViewById(R.id.hour);
		    	    	tvAPM = (TextView)view.findViewById(R.id.apm);
		    	    	tvDAYS = (TextView)view.findViewById(R.id.daysofweek);
		    	    	tvGUBUN = (TextView)view.findViewById(R.id.gubun);
		    			
						switch(e.getAction()){
							case MotionEvent.ACTION_DOWN:
							case MotionEvent.ACTION_MOVE:
								rowLayout.setBackgroundResource(R.drawable.list_pressed_bg);								
								tvMINUTES.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor_inverse)));
	                            tvHOUR.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor_inverse)));
	                            tvAPM.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor_inverse)));
	                            tvDAYS.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor_inverse))); //kyj
	                            tvGUBUN.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor_inverse)));
								return false;
							case MotionEvent.ACTION_CANCEL:
							case MotionEvent.ACTION_UP:
							default:
							    rowLayout.setBackgroundColor(Color.parseColor(getResources().getString(R.color.list_backgroundColor)));
							    tvMINUTES.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
	                            tvHOUR.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
	                            tvAPM.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
	                            tvDAYS.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
	                            tvGUBUN.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
								return false;
						}
		    		}
		    	});
		    	*/
			boolean is24HourFormat = DateFormat.is24HourFormat(testlist);


                        /* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
                         * 15/02/12 pradeep.gk@lge.com.
                         * To support arabic and farsi number conversion support.
                         */
                        if(CommonUtil.isArabFarsiLanguage()){
                            if (Integer.toString(minutes).length() == 1) {
                                (holder.tvMINUTES).setText(CommonUtil.convertArabFarsiNum(("0" + Integer.toString(minutes)),false));
                            } else {
                                (holder.tvMINUTES).setText( CommonUtil.convertArabFarsiNum((Integer.toString(minutes)),false));
                            }
                            if (is24HourFormat == true) {
                                if (Integer.toString(hour).length() == 1) {
                                    (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum(("0" +  Integer.toString(hour)),false));
                                } else {
                                    (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum((Integer.toString(hour)),false));
                                }
                                (holder.tvAPM).setVisibility(View.GONE);
                            } else {
                                if (hour >= 13 && hour <= 23) {
                                    (holder.tvHOUR).setText( CommonUtil.convertArabFarsiNum((Integer.toString(hour-12)),false));
                                } else if (hour == 0) {
                                    (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum("12",false));
                                } else {
                                    (holder.tvHOUR).setText(CommonUtil.convertArabFarsiNum((Integer.toString(hour)),false));
                                }
                                (holder.tvAPM).setVisibility(View.VISIBLE);
                                if (hour >= 0 && hour <= 11) {
                                   (holder.tvAPM).setText( R.string.sp_AM_string_NORMAL);
                                } else {
                                   (holder.tvAPM).setText( R.string.sp_PM_string_NORMAL);
                                }
                            }
                        }else{
                        /* LGSI_CHANGE_E: Arabic and Farsi number conversion support. */
		    	if (Integer.toString(minutes).length() == 1) {       
					(holder.tvMINUTES).setText("0" + Integer.toString(minutes));  
				} else {
					(holder.tvMINUTES).setText( Integer.toString(minutes));  
				}       
				//////////////////////////////////////////////////////////////
				 

				if (is24HourFormat == true) {
					if (Integer.toString(hour).length() == 1) {
						(holder.tvHOUR).setText("0" +  Integer.toString(hour));
					} else {
						(holder.tvHOUR).setText(Integer.toString(hour));
					}
					 
					(holder.tvAPM).setVisibility(View.GONE); 
				} else {
					if (hour >= 13 && hour <= 23) {
						(holder.tvHOUR).setText( Integer.toString(hour-12));
					} else if (hour == 0) {
						(holder.tvHOUR).setText("12");
					} else {
						(holder.tvHOUR).setText(Integer.toString(hour));
					}
	       			////////////////////////////////////////////////////////////////////////////////////////	         
					(holder.tvAPM).setVisibility(View.VISIBLE); 				
					if (hour >= 0 && hour <= 11) {
						(holder.tvAPM).setText( R.string.sp_AM_string_NORMAL);
					} else {
						(holder.tvAPM).setText( R.string.sp_PM_string_NORMAL);
                              /* LGSI_CHANGE_S: Arabic and Farsi number conversion support.
                               * 15/02/12 pradeep.gk@lge.com.
                               * To support arabic and farsi number conversion support.
                               */
                                  }
                              /* LGSI_CHANGE_E: Arabic and Farsi number conversion support. */
					}   
				}    
				//////////////////////////////////////////////////////////////
	    			 
				(holder.tvDAYS).setText(daysOfWeek.toString(testlist));
				String strWidgetYN = (String)storageWidgetYN.get(id);
				 
				LinearLayout eee = (LinearLayout)view.findViewById(R.id.eee);                       
				//LinearLayout aa = (LinearLayout)eee.findViewById(R.id.abcd);
				//final String enabled = cursor.getString(4);
				
				eee.setVisibility(View.GONE);
				  
				///////////////////////////////////////////////////////////////////////
				// check YN 
				String strCheckingYN = (String)storageCheck.get(id); 	
				
		        if(false == mIsShowCheck) {   
		        	//eee.setVisibility(View.GONE);
		        	holder.checkView.setVisibility(View.GONE); 
		        } 
		        else {
		        	if ("N".equalsIgnoreCase(strWidgetYN)) {
		        		 eee.setVisibility(View.GONE);  
		        		 holder.checkView.setVisibility(View.VISIBLE);
			        	 
		        		 int cursorPosition = cursor.getPosition();
		        		 holder.checkView.setTag(cursorPosition);		        		 
		        		 holder.checkView.setChecked("1".equals(strCheckingYN));                     
		        	}
	       		}

	    	}
            ///////////////////////////////////////////////////////////////////////
	    }
	  
	    // 20101019_mhkwon_Block multi touch [[
	    Handler blockMultiTouchHandler = new Handler();
	    Runnable blockMultiTouchThread = new Runnable() {
	    	public void run() {
	    		bBlockMultiTouchFlag = false;
	        };
	    };
	    //20101019_mhkwon_Block multi touch ]]
	    
	    /**
	     * Returns the {@link ViewBinder} used to bind data to views.
	     *
	     * @return a ViewBinder or null if the binder does not exist
	     *
	     * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
	     * @see #setViewBinder(android.widget.AlarmListCursorAdapter.ViewBinder)
	     */
	    public ViewBinder getViewBinder() {
	        return mViewBinder;
	    }

	    /**
	     * Sets the binder used to bind data to views.
	     *
	     * @param viewBinder the binder used to bind data to views, can be null to
	     *        remove the existing binder
	     *
	     * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
	     * @see #getViewBinder()
	     */
	    public void setViewBinder(ViewBinder viewBinder) {
	        mViewBinder = viewBinder;
	    }

	    /**
	     * Called by bindView() to set the image for an ImageView but only if
	     * there is no existing ViewBinder or if the existing ViewBinder cannot
	     * handle binding to an ImageView.
	     *
	     * By default, the value will be treated as an image resource. If the
	     * value cannot be used as an image resource, the value is used as an
	     * image Uri.
	     *
	     * Intended to be overridden by Adapters that need to filter strings
	     * retrieved from the database.
	     *
	     * @param v ImageView to receive an image
	     * @param value the value retrieved from the cursor
	     */
	    public void setViewImage(ImageView v, String value) {
	        try {
	            v.setImageResource(Integer.parseInt(value));
	        } catch (NumberFormatException nfe) {
	            v.setImageURI(Uri.parse(value));
	        }
	    }

	    /**
	     * Called by bindView() to set the text for a TextView but only if
	     * there is no existing ViewBinder or if the existing ViewBinder cannot
	     * handle binding to an TextView.
	     *
	     * Intended to be overridden by Adapters that need to filter strings
	     * retrieved from the database.
	     * 
	     * @param v TextView to receive text
	     * @param text the text to be set for the TextView
	     */    
	    public void setViewText(TextView v, String text) {
	        v.setText(text);
	    }

	    /**
	     * Return the index of the column used to get a String representation
	     * of the Cursor.
	     *
	     * @return a valid index in the current Cursor or -1
	     *
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     * @see #setStringConversionColumn(int) 
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getCursorToStringConverter()
	     */
	    public int getStringConversionColumn() {
	        return mStringConversionColumn;
	    }

	    /**
	     * Defines the index of the column in the Cursor used to get a String
	     * representation of that Cursor. The column is used to convert the
	     * Cursor to a String only when the current CursorToStringConverter
	     * is null.
	     *
	     * @param stringConversionColumn a valid index in the current Cursor or -1 to use the default
	     *        conversion mechanism
	     *
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     * @see #getStringConversionColumn()
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getCursorToStringConverter()
	     */
	    public void setStringConversionColumn(int stringConversionColumn) {
	        mStringConversionColumn = stringConversionColumn;
	    }

	    /**
	     * Returns the converter used to convert the filtering Cursor
	     * into a String.
	     *
	     * @return null if the converter does not exist or an instance of
	     *         {@link android.widget.AlarmListCursorAdapter.CursorToStringConverter}
	     *
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter)
	     * @see #getStringConversionColumn()
	     * @see #setStringConversionColumn(int)
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     */
	    public CursorToStringConverter getCursorToStringConverter() {
	        return mCursorToStringConverter;
	    }

	    /**
	     * Sets the converter  used to convert the filtering Cursor
	     * into a String.
	     *
	     * @param cursorToStringConverter the Cursor to String converter, or
	     *        null to remove the converter
	     *
	     * @see #setCursorToStringConverter(android.widget.AlarmListCursorAdapter.CursorToStringConverter) 
	     * @see #getStringConversionColumn()
	     * @see #setStringConversionColumn(int)
	     * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
	     */
	    public void setCursorToStringConverter(CursorToStringConverter cursorToStringConverter) {
	        mCursorToStringConverter = cursorToStringConverter;
	    }

	    /**
	     * Returns a CharSequence representation of the specified Cursor as defined
	     * by the current CursorToStringConverter. If no CursorToStringConverter
	     * has been set, the String conversion column is used instead. If the
	     * conversion column is -1, the returned String is empty if the cursor
	     * is null or Cursor.toString().
	     *
	     * @param cursor the Cursor to convert to a CharSequence
	     *
	     * @return a non-null CharSequence representing the cursor
	     */
	    @Override
	    public CharSequence convertToString(Cursor cursor) {
	    	if(cursor != null) {
	    		if (mCursorToStringConverter != null) {
		            return mCursorToStringConverter.convertToString(cursor);
		        } else if (mStringConversionColumn > -1) {
		            return cursor.getString(mStringConversionColumn);
		        }
	    	}
	        return super.convertToString(cursor);
	    }
     
	    /**
	     * Create a map from an array of strings to an array of column-id integers in mCursor.
	     * If mCursor is null, the array will be discarded.
	     * 
	     * @param from the Strings naming the columns of interest
	     */
        private void findColumns(String[] from) {
            try {
                Cursor mCursor = getCursor();
                if (mCursor != null) {
                    int i;
                    int count = from.length;
                    if (mFrom == null || mFrom.length != count) {
                        mFrom = new int[count];
                    }
                    for (i = 0; i < count; i++) {
                        mFrom[i] = mCursor.getColumnIndexOrThrow(from[i]);
                    }
                } else {
                    mFrom = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                if (mCursor != null) {
//                    mCursor.close();
//                }
            }
        }

	    @Override
	    public void changeCursor(Cursor c) {
	        super.changeCursor(c);
	        // rescan columns in case cursor layout is different
	        findColumns(mOriginalFrom);
	    }
	                     
	    /**
	     * Change the cursor and change the column-to-view mappings at the same time.
	     *  
	     * @param c The database cursor.  Can be null if the cursor is not available yet.
	     * @param from A list of column names representing the data to bind to the UI.  Can be null 
	     *            if the cursor is not available yet.
	     * @param to The views that should display column in the "from" parameter.
	     *            These should all be TextViews. The first N views in this list
	     *            are given the values of the first N columns in the from
	     *            parameter.  Can be null if the cursor is not available yet.
	     */
	    public void changeCursorAndColumns(Cursor c, String[] from, int[] to) {
	        mOriginalFrom = from;
	        mTo = to;
	        super.changeCursor(c);        
	        findColumns(mOriginalFrom);
	    }
	}        
	//============ class End==========
	private int deleteCount = 0;
	public void checkEvent(String id, View view) {
		
		CheckedTextView checkAll = (CheckedTextView) findViewById(R.id.checkall);
		String strValue = storageCheck.get(id);
		        
        if ("1".equals(strValue)) {
 	   		storageCheck.put(id, "0");
 	   		CheckedTextView chk = (CheckedTextView) view.findViewById(R.id.CheckBox);
 	   		chk.setChecked(false);
            deleteCount--;
        } 
        else if ("0".equals(strValue)) {
        	storageCheck.put(id, "1");
        	CheckedTextView chk = (CheckedTextView) view.findViewById(R.id.CheckBox);
        	chk.setChecked(true);
    		deleteCount++;
            // to do
        } ///////////////////////////////////////////////////////////////////////////
        Log.d(tag, "id = " + id);
        
        checkAll.setChecked( deleteCount == listCount );
        setSelectedItem(deleteCount);
        
        Map.Entry<String, String>temp;
        Set ee = storageCheck.entrySet();
        Iterator ii = ee.iterator();
        boolean delKey_checkYN = false;
        
        while(ii.hasNext()) {
        	temp = (Map.Entry<String, String>) ii.next();
        	if ("1".equals(temp.getValue())) {
        		delKey_checkYN = true;
      		  	mDeleteButton.setEnabled(true);
      		  	return;
        	}
        }
        
        if (delKey_checkYN == false) {
        	mDeleteButton.setEnabled(false);
        }

    }
    
	public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
		/*[START] 2012.03.02 suein1209.kim set check box listener*/
		checkEvent(((ViewHolder)view.getTag()).id, view);
		/*[END] 2012.03.02 suein1209.kim set check box listener*/
	}   
	
	private void setSelectedItem(int select){		
		mDeleteCount = (TextView)findViewById(R.id.SelectedItem);
		if(mDeleteCount != null )
			mDeleteCount.setText(String.format(getString(R.string.sp_selected_NORMAL),	select));
	} 
}  
